package com.sihan.framework.etm.interceptor;

import com.framework.model.ApiResult;
import com.framework.util.JsonUtils;
import com.sihan.framework.etm.service.OperatorService;
import com.sihan.framework.etm.service.SecurityParamService;
import com.sihan.framework.etm.service.UserService;
import lombok.Data;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author QinC
 * @create 2018-09-12 9:47
 */
@Data
public class AuthHandlerInterceptor implements HandlerInterceptor {

    private UserService userService;

    private SecurityParamService securityParamService;
    
    private OperatorService operatorService;
    
    protected final static boolean r = true;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String uri = request.getRequestURI();

//       /* if(hasSpecialChars(request)) {
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("application/json;charset=utf-8");
//            PrintWriter writer = response.getWriter();
//            writer.write(JsonUtils.toJsonString(ApiResult.failed("不允许输入特殊字符")));
//            writer.flush();
//            return false;
//        }*/
//
//        /*boolean b = filterRefer(request);
//        if(!b){
//            return false;
//        }*/
//
//        //强制修改密码拦截、已经登录了
//        if(isUpdatePsd()) {
//            if(!"/key".equals(uri) && !"/initcpwd".equals(uri) && !"/user/password/update".equals(uri)
//                    && !"/user/logout".equals(uri)) {
//                response.sendRedirect(request.getContextPath() + "/initcpwd");
//                return false;
//            }
//        }
//
//        //会话还在
//        Session session = SecurityUtils.getSubject().getSession();
//        User sessionUser = WebUtils.user();
//        if(sessionUser != null) {
//            User newUser = userService.selectOne(new Condition<>(new User(sessionUser.getUsername())));
//
//            MD5 md5 = MD5.getInstance();
//            Encrypt encrypt = md5.encode(session.getId() + session.getHost() + request.getHeader("user-agent"));
//            if(!encrypt.toHex().equals(session.getAttribute("HASH_ID").toString())) {
//                PrintWriter writer = response.getWriter();
//                writer.write("Illegal session hijacking");
//                writer.flush();
//                return false;
//            }
//
//
//            //登录IP判定
//            if(StringUtils.isNotBlank(newUser.getLoginIp())) {
//                if(!newUser.getLoginIp().equals(SecurityUtils.getSubject().getSession().getHost())) {
//                    SecurityUtils.getSubject().logout();
//                    //重定向到登录页面
//                    response.sendRedirect(request.getContextPath() + "/login");
//                    return false;
//                }
//            }
//
//
//            //当前时间是否允许访问
//            Date now = new Date();
//            if(newUser.getAccessStartTime() == null && newUser.getAccessEndTime() != null) {
//                if(now.after(newUser.getAccessEndTime())) {
//                    response.sendRedirect(request.getContextPath() + "/login");
//                    return false;
//                }
//            } else if(newUser.getAccessStartTime() != null && newUser.getAccessEndTime() == null) {
//                if(now.before(newUser.getAccessStartTime())) {
//                    response.sendRedirect(request.getContextPath() + "/login");
//                    return false;
//                }
//            } else if(newUser.getAccessStartTime() != null && newUser.getAccessEndTime() != null) {
//                if(now.before(newUser.getAccessStartTime()) || now.after(newUser.getAccessEndTime())) {
//                    response.sendRedirect(request.getContextPath() + "/login");
//                    return false;
//                }
//            }
//        }
    	
        if(!operatorService.validate(handler)) {
        	response.setHeader("Access-Control-Allow-Origin",  request.getHeader("Origin"));
        	response.setHeader("Access-Control-Allow-Credentials", "true");
        	response.setContentType("application/json; charset=utf-8");
        	response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            ApiResult<?> result = ApiResult.fail("401","没有权限");
            out.println(JsonUtils.toJsonString(result));
            out.flush();
            out.close();
            //response.sendRedirect(request.getContextPath() + "/permition");
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }

//
//    private boolean filterRefer(HttpServletRequest request){
//        String referrer = request.getHeader("referer");
//        String basePath = request.getScheme()+"://"+request.getServerName();
//        //防盗链
//        if(referrer==null||"".equals(referrer.trim())||referrer.startsWith(basePath)){
//            return true;
//        }
//        else{
//            return false;
//        }
//    }
//
//    private boolean isUpdatePsd() {
//        User sessionUser = WebUtils.user();
//        if(sessionUser != null) {
//            User newUser = userService.selectOne(new Condition<>(new User(sessionUser.getUsername())));
//            Date date = newUser.getUpdatePsdTime();
//            Date now = new Date();
//            //获取口令有效期
//            SecurityParam sp = securityParamService.getSecurity();
//            if(date == null || now.getTime() - date.getTime() > sp.getPsd().intValue() * 30 * 24 * 60 * 60 * 1000L) {
//                return true;
//            } else {
//                return false;
//            }
//        } else {
//            return false;
//        }
//    }
//
//    private boolean hasSpecialChars(HttpServletRequest request) {
//        Map<String, String[]> map = request.getParameterMap();
//        Set<Map.Entry<String, String[]>> set = map.entrySet();
//       for(Map.Entry<String, String[]> se : set) {
//           String[] values = se.getValue();
//
//           if (!(values == null || values.length == 0)) {
//               for (int i = 0; i < values.length; i++) {
//                   if(StringUtils.isNotBlank(values[i]) && RegexpUtils.isSpecialCharacters(values[i])) {
//                       return true;
//                   }
//               }
//           }
//       }
//
//       return false;
//    }
}
